﻿using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace client.helpers
{
    public static class AESHelper
    {
        private static string Key = "tms-sqlite-databese-password-key";
        private static string IV = "databesepassword";

        public static string Encrypt(string plainText)
        {
            // Convert the plaintext string to a byte array.  
            byte[] encrypted;

            // Create an AesCryptoServiceProvider object  
            // with the specified key and IV.  
            using (Aes aesAlg = Aes.Create())
            {
                aesAlg.Key = Encoding.UTF8.GetBytes(Key);
                aesAlg.IV = Encoding.UTF8.GetBytes(IV);

                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            swEncrypt.Write(plainText);
                        }
                        encrypted = msEncrypt.ToArray();
                    }
                }
            }

            // Return the encrypted bytes from the memory stream.  
            return Convert.ToBase64String(encrypted);
        }

        public static string Decrypt(string encryptedText)
        {
            // Convert the encrypted text string to a byte array.  
            byte[] cipherText = Convert.FromBase64String(encryptedText);

            // Create an AesCryptoServiceProvider object  
            // with the specified key and IV.  
            using (Aes aesAlg = Aes.Create())
            {
                aesAlg.Key = Encoding.UTF8.GetBytes(Key);
                aesAlg.IV = Encoding.UTF8.GetBytes(IV);

                ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

                using (MemoryStream msDecrypt = new MemoryStream(cipherText))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {
                            // Read the decrypted bytes from the decrypting stream  
                            // and return them as a string.  
                            return srDecrypt.ReadToEnd();
                        }
                    }
                }
            }
        }
    }
}
